import subprocess
import argparse
import os
import requests
import time
import sys
import qrcode

PGYER_API_KEY = "29f1843562f33145cc77419ed78ae446"

def print_step(message):
    print(f"\n\033[1;34m=== {message} ===\033[0m")

def run_command(command, cwd=None):
    print(f"\033[0;32m执行命令: {command}\033[0m")
    process = subprocess.Popen(command, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    while True:
        output = process.stdout.readline()
        if output == b'' and process.poll() is not None:
            break
        if output:
            print(output.decode().strip())
    
    rc = process.poll()
    if rc != 0:
        error = process.stderr.read().decode()
        print(f"\033[1;31m错误: {error}\033[0m")
        raise Exception(f"命令执行失败: {command}")
    return rc

def build_android():
    print_step("开始构建Android Release包")
    
    # 清理构建缓存
    print_step("清理构建缓存")
    run_command("cd android && ./gradlew clean", cwd=os.getcwd())
    
    # 构建APK
    print_step("构建APK")
    run_command("cd android && ./gradlew assembleRelease", cwd=os.getcwd())
    
    # 查找APK文件
    apk_path = os.path.join(os.getcwd(), "android/app/build/outputs/apk/release/Proergy.apk")
    if not os.path.exists(apk_path):
        raise Exception("APK文件未找到")
    
    print(f"\033[1;32m构建成功: {apk_path}\033[0m")
    return apk_path

def build_ios():
    print_step("开始构建iOS Release包")
    
    # 安装依赖
    print_step("安装Pod依赖")
    run_command("cd ios && pod install", cwd=os.getcwd())
    
    # 清理构建
    print_step("清理构建")
    run_command("xcodebuild clean -workspace ios/leosmart.xcworkspace -scheme leosmart -configuration Release", cwd=os.getcwd())
    
    # 构建archive
    print_step("构建Archive")
    archive_path = os.path.join(os.getcwd(), "ios/build/leosmart.xcarchive")
    run_command(f"xcodebuild archive -workspace ios/leosmart.xcworkspace -scheme leosmart -configuration Release -archivePath {archive_path} -destination 'generic/platform=iOS'", cwd=os.getcwd())
    
    # 导出IPA
    print_step("导出IPA")
    export_path = os.path.join(os.getcwd(), "ios/build/Release-iphoneos")
    run_command(f"xcodebuild -exportArchive -archivePath {archive_path} -exportPath {export_path} -exportOptionsPlist ios/ExportOptionsAdHoc.plist", cwd=os.getcwd())
    
    # 查找IPA文件
    ipa_path = os.path.join(export_path, "leosmart.ipa")
    if not os.path.exists(ipa_path):
        raise Exception("IPA文件未找到")
    
    print(f"\033[1;32m构建成功: {ipa_path}\033[0m")
    return ipa_path

def upload_to_pgyer(file_path, platform: str):
    print_step(f"开始上传{platform}包到蒲公英，获取上传配置...")
    
    token_response = requests.post('https://api.pgyer.com/apiv2/app/getCOSToken', data={
        '_api_key': PGYER_API_KEY,
        'buildType': platform,
    })
    token_result = token_response.json()['data']
    print_step('拿到上传配置，上传文件中...')

    upload_url = token_result['endpoint']
    
    upload_data = {
        '_api_key': PGYER_API_KEY,
        'key': token_result['key'],
        'signature': token_result['params']['signature'],
        'x-cos-security-token': token_result['params']['x-cos-security-token'],
        'buildUpdateDescription': f'{platform} Release Build - {time.strftime("%Y-%m-%d %H:%M:%S")}'
    }
    files = {
        'file': open(file_path, 'rb')
    }
    upload_response = requests.post(upload_url, data=upload_data, files=files)
    if upload_response.status_code != 204:
        print_step('上传失败了')
        raise Exception(f"上传失败: {upload_response.text}")
    print_step('文件上传完成，等待查询结果...')
    for i in range(10, 0, -1):
        print(f"请等待 {i} 秒钟，等待蒲公英处理安装包完成...", end='\r')  # \r 让光标回到行首
        time.sleep(1)
    print_step('开始查询上传结果...')
    check_response = requests.post('https://api.pgyer.com/apiv2/app/buildInfo', data={'_api_key': PGYER_API_KEY, 'buildKey': token_result['key']})
    check_result = check_response.json()
    succeed = check_result['code'] == 0
    if succeed:
        print_step('上传成功，扫码下载')
        qr = qrcode.QRCode(
                        version=1,
                        error_correction=qrcode.constants.ERROR_CORRECT_L,
                        box_size=2,  # 控制终端显示的二维码大小
                        border=1,
                    )
        qr.add_data('https://www.pgyer.com/tsunpro')  # 二维码内容
        qr.make(fit=True)
        qr.print_ascii(invert=True)
    else:
        raise Exception(f'发布失败，具体内容：{check_result}')

def get_default_file_path(platform):
    """获取各平台默认构建文件路径"""
    if platform == 'android':
        return os.path.join(os.getcwd(), "android/app/build/outputs/apk/release/TSUN Pro.apk")
    elif platform == 'ios':
        return os.path.join(os.getcwd(), "ios/build/Release-iphoneos/leosmart.ipa")
    return None

def main():
    parser = argparse.ArgumentParser(description='React Native自动构建脚本')
    parser.add_argument('--platform', '-p', required=True, choices=['android', 'ios'], help='构建平台: android 或 ios')
    parser.add_argument('--skip-build', '-sb', action='store_true', help='跳过构建过程，直接上传')
    parser.add_argument('--skip-upload', '-su', action='store_true', help='仅构建不上传，构建完成后输出文件路径')
    parser.add_argument('--file', help='指定要上传的文件路径（跳过构建时使用）')
    args = parser.parse_args()
    
    try:
        if args.skip_build and args.skip_upload:
            raise Exception("参数冲突：不能同时使用 --skip-build 和 --skip-upload")
        file_path = None
        
        if args.skip_build:
            # 跳过构建，直接上传
            if args.file:
                file_path = args.file
            else:
                file_path = get_default_file_path(args.platform)
                if not file_path or not os.path.exists(file_path):
                    raise Exception(f"未找到默认{args.platform}构建文件，请使用--file指定路径")
            
            print_step(f"跳过构建，直接上传文件: {file_path}")
        else:
            run_command(f'pnpm install')
            # 正常构建流程
            if args.platform == 'android':
                file_path = build_android()
            elif args.platform == 'ios':
                file_path = build_ios()
        
        # 仅构建不上传
        if args.skip_upload:
            if not file_path:
                raise Exception("未获取到有效的文件路径")
            print_step("仅构建完成，构建产物路径：")
            print(file_path)
            print_step("流程完成")
            return
        
        # 上传到蒲公英
        if file_path:
            upload_to_pgyer(file_path, args.platform)
        else:
            raise Exception("未获取到有效的文件路径")
            
        print_step("流程完成")
    except Exception as e:
        print(f"\033[1;31m错误: {str(e)}\033[0m")
        sys.exit(1)

if __name__ == "__main__":
    main()